// functions/hello/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cake-shop-001-gppbo'
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate
const utils = require('./utils')

const test1 = async (event, context) => {
  // 这里是用来 修改 products 中的 cascaderText 中的错误，比如“走进永昌/走进永昌”
  db.collection('products').aggregate()
    .lookup({
      from: 'categorys',
      localField: 'categoryId',
      foreignField: '_id',
      as: 'test'
    })
    .end()
    .then(res => console.log(res, res.list[0]._id, typeof (res.list[0]._id)))
    .catch(err => console.error(err))
}

const test2 = async (event, context) => {
  db.collection('products').aggregate()
    .lookup({
      from: 'categorys',
      let: {
        products_categoryId: '$categoryId',
      },
      pipeline: $.pipeline()
        .match(_.expr($.and([$.eq(['$_id', '$$products_categoryId'])])))
        .done(),
      as: 'test_pipeline'
    })
    .end()
    .then(res => console.log(res, res.list[0]._id, typeof (res.list[0]._id)))
    .catch(err => console.error(err))
}


const test3 = async (event, context) => {
  const test1 = new Object('5de328e2e887230e08f4fdf8')
  const test2 = await db.collection('categorys').where({
    _id: '5de328e2e887230e08f4fdf8'
  }).get()
  const test3 = await db.collection('products').where({
    categoryId: '5de328e2e887230e08f4fdf8'
  }).get()

  return {
    test1,
    test2,
    test3
  }
}

const test4 = async (event, context) => {
  // db.collection('newproducts').aggregate()
  //   .lookup({
  //     from: 'newcategorys',
  //     let: {
  //       products_categoryId: ObjectID.createFromHexString('$categoryId'),
  //     },
  //     pipeline: $.pipeline()
  //       .match(_.expr($.and([$.eq(['$_id', '$$products_categoryId'])])))
  //       .done(),
  //     as: 'test_pipeline'
  //   })
  //   .end()
  //   .then(res => console.log(res, res.list[0]._id, typeof (res.list[0]._id)))
  //   .catch(err => console.error(err))
}

const test5 = async (event, context) => {
  // 这里是用来 修改 products 中的 cascaderText 中的错误，比如“走进永昌/走进永昌”
  try {
    // const result = await db.collection('categorys').where({
    //   _id: "5de31d24b0f80726901430c9"
    // }).get()

    // 也可以这样查找
    const result = await db.collection('categorys').doc("5de31d24b0f80726901430c9").get()
    console.log('result', result)
  } catch (error) {
    console.log(error)
  }
}

const test6 = async (event, context) => {
  try {
    const result = await db.collection('newproducts').doc('5e47911f12dd9731b45b9261').update({
      data: {
        title: "轮播图22",
        lastTime: db.serverDate()
      }
    })
    console.log('result', result)
  } catch (error) {
    console.log(error)
  }
}

const test7 = async (event, context) => {
  try {
    const page = 1
    const size = 10
    const result = await db.collection("messages_boards")
      .where({})
      .skip((page - 1) * size)
      .limit(size)
      .orderBy('_id', 'desc')
      .get()

    console.log('result', result)
  } catch (error) {
    console.log(error)
  }
}

const test8 = async (event, context) => {
  try {
    const result = await db.collection("messages_boards")
      .where({})
      .count()

    console.log('result', result)
  } catch (error) {
    console.log(error)
  }
}

const test9 = async (event, context) => {
  try {
    let {
      data: dataTemp
    } = await db.collection("ask_details_lists").get()


    const result = dataTemp.map(async e => {
      const {
        _id
      } = e
      try {
        const resultData = await db.collection("asks").where({
          _id
        }).get()
        console.log(resultData)
      } catch (error) {
        console.log('111111', error)
      }


      // let dataResult = {
      //   ...e
      // }

      // dataResult.ask = {
      //   ...data
      // }

      // return dataResult
    })

    console.log('result', result)
  } catch (error) {
    console.log(error)
  }
}

const test10 = async (event, context) => {
  return {
    success: 11111111111111
  }
}

const test11 = async (event, context) => {

  // 这是“走进永昌”，这个一级分类的id
  const pCategoryId = '5de31d24b0f80726901430c9'
  // 过滤 轮播图
  const filterId = '5de328e2e887230e08f4fdf8'

  try {
    const {
      data: resultProduct
    } = await db.collection("products").where({
      pCategoryId
    }).get()
    const dataProduct = utils.goDataFilter(resultProduct)
    const {
      data: resultCategory
    } = await db.collection("categorys").where({
      parentId: pCategoryId
    }).get()
    // 这里要 转化为string类型
    const dataCategory = resultCategory
      .filter((item) => item._id + '' !== filterId)
      .map((item) => ({
        text: item.name
      }))
    let temp = {
      ...dataCategory[2]
    }
    dataCategory[2] = {
      ...dataCategory[3]
    }
    dataCategory[3] = temp

    // todo 这里需要好好修改
    dataCategory[0].url = '/images/index/nav_service.png'
    dataCategory[1].url = '/images/index/nav_show.png'
    dataCategory[2].url = '/images/index/nav_center.png'
    dataCategory[3].url = '/images/index/nav_about.png'
    dataCategory[4].url = '/images/index/nav_call.png'

    return {
      ...dataProduct,
      listNav: dataCategory
    }

  } catch (error) {

    return {
      status: 1,
      msg: '获取“走进永昌”信息失败。',
      error
    }

  }

}

const test12 = async (event, context) => {
  const {
    result
  } = await cloud.callFunction({
    name: 'go',
    data: {
      $url: '/imagesOfTitles',
      other: {}
    }
  })

  return result
}

const test13 = async (event, context) => {
  const listCount = 10
  const skipCount = 0
  const result = await db.collection("products")
    .aggregate()
    .match({
      pCategoryId: '5de31d5fb0f80726901430ca',
      status: 1,
      title: _.neq('轮播图')
    })
    .limit(listCount * 1)
    .skip(skipCount * 1)
    .sort({
      _id: -1
    })
    .project({
      _id: 0,
      categoryId: 0,
      pCategoryId: 0
    })
    .end()

  return result
}

const test14 = async (event, context) => {
  const listCount = 10
  const skipCount = 0
  const cName = '推荐'

  // 精选案例这个分类本身的id
  const parentId = '5de31d5fb0f80726901430ca'

  /**
   * cName有可能是“推荐”、“办公楼宇”、“商业展示”和“”家居软装。
   * 如果是“推荐”，那么是得不到数据的，需要返回“精选案例”下的listCount数量。
   * 如果是别的，那么直接使用resultCNameId.parentId所代表的种类id查找，返回数据。
   */
  const {
    data: resultCNameId
  } = await db.collection("categorys").where({
    name: cName
  }).get()

  const condition = resultCNameId.length > 0 ?
    // 根据所属分类查找
    {
      categoryId: resultCNameId[0]._id,
      status: 1,
      title: _.neq('轮播图')
    } :
    // 根据所属分类的父分类查找，这里的父分类是“精选案例”。
    {
      pCategoryId: parentId,
      status: 1,
      title: _.neq('轮播图')
    }

  const {
    list
  } = await db.collection("products")
    .aggregate()
    .match(condition)
    .limit(listCount * 1)
    .skip(skipCount * 1)
    .sort({
      _id: -1
    })
    .project({
      _id: 0,
      categoryId: 0,
      pCategoryId: 0
    })
    .end()

  return list
}

const test15 = async (event, context) => {
  const {
    data: resultCNameId
  } = await db.collection("categorys").where({
    name: '推荐'
  }).get()

  return resultCNameId
}

const test16 = async (event, context) => {

  // 精选案例
  const categoryId = "5de31d5fb0f80726901430ca"
  // 办公楼宇
  const pCategoryId = "5de32fd06896be05f40883b8"
  const pageNum = 2
  const pageSize = 5

  let condition

  if (undefined !== categoryId && undefined !== pCategoryId) {

    condition = {
      categoryId,
      pCategoryId
    }
    // condition = {
    //   categoryId: db.RegExp({
    //     regexp: `^.*${categoryId}.*$`,
    //     options: 'i',
    //   }),
    //   pCategoryId: db.RegExp({
    //     regexp: `^.*${pCategoryId}.*$`,
    //     options: 'i',
    //   })
    // }

  } else if (undefined !== pCategoryId && undefined === categoryId) {

    condition = {
      pCategoryId
    }

  }

  try {

    const result = await db.collection("products")
      .where({
        pCategoryId
      })
      .get()

    return result

    // const {
    //   total
    // } = await db.collection("products")
    //   .where({
    //     ...condition
    //   })
    //   .count()

    // const {
    //   data: list
    // } = await db.collection("products")
    //   .where({
    //     ...condition
    //   })
    //   .skip((pageNum - 1) * pageSize)
    //   .limit(pageSize)
    //   .orderBy('lastTime', 'desc')
    //   .get()

    // return {total, list}

  } catch (error) {

    return error

  }
}

const test17 = async (event, context) => {
  let {
    data: details
  } = await db.collection("ask_details_lists").orderBy('_id', 'desc').get()

  const {
    data: asks_data
  } = await db.collection("asks").where({}).get()

  details.forEach(e_details => {
    const {
      ask: askId
    } = e_details

    const newList = asks_data.filter(item => item._id === askId)
    if (newList && newList.length > 0) e_details.ask = newList
  })

  return details
}

const test18 = async (event, context) => {
  const wxContext = cloud.getWXContext()

  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}

const test19 = async (event, context) => {

  const temp = {
    other: {
      page: 1,
      size: 10,
      status: '0'
    }
  }

  let {
    page,
    size,
    name,
    phone: telephone,
    message: textarea,
    status,
    type,
  } = temp.other

  let condition = {}
  if (name) {
    condition = {
      name: new db.RegExp({
        regexp: `^.*${name}.*$`,
        options: 'i'
      })
    }
  } else if (telephone) {
    condition = {
      telephone: new db.RegExp({
        regexp: `^.*${telephone}.*$`,
        options: 'i'
      })
    }
  } else if (textarea) {
    condition = {
      textarea: new db.RegExp({
        regexp: `^.*${textarea}.*$`,
        options: 'i'
      })
    }
  } else if (status) {
    condition = {
      status
    }
  }

  const getAllData = async () => {
    // 如果这里使用聚合，那么得到的数据中 _id 是一个ObjectId。
    // mongodb数据的坑爹就在这里了。
    const {
      data: tempResultAsk
    } = await db.collection("ask_details_lists").where({})
      .skip((page - 1) * size)
      .limit(size)
      .orderBy('_id', 'desc')
      .get()

    const {
      data: asks
    } = await db.collection('asks').where({}).get()

    tempResultAsk.forEach(e_temp => {
      e_temp.ask = asks.filter(e_asks => e_asks._id + '' === e_temp.ask)
    })

    console.log('tempResultAsk', tempResultAsk)
    console.log('asks', asks)

    return [...tempResultAsk]
  }


  try {
    page = page * 1 || 1
    size = size * 1 || 1

    let total, resultMsg, data

    // 如果是按照咨询种类查询。
    if (type) {
      const tempResultAsk = await getAllData()

      const resultAsk = tempResultAsk.filter((item) => item.ask._id + '' === type)

      total = resultAsk.length
      resultMsg = resultAsk
      data = {
        pageNum: page,
        total,
        pages: Math.ceil(total / size),
        pageSize: size,
        list: resultMsg || [],
      }
    } else {
      const {
        total
      } = await db.collection('ask_details_lists').where(condition).count()

      const list = await getAllData()

      data = {
        pageNum: page,
        total,
        pages: Math.ceil(total / size),
        pageSize: size,
        list,
      }
    }

    // ctx.body = getSuccessData(data)
    return data

  } catch (error) {

    /**
     * page: 1
     * size: 10
     * status: "1"
     */
    // ctx.body = getFailData({
    //   msg: "留言板获取信息失败。",
    //   error: {
    //     page,
    //     size,
    //     name,
    //     phone: telephone,
    //     message: textarea,
    //     status,
    //     type,
    //   }
    // })

    return error

  }


}

const test20 = async (event, context) => {
  let updateInfo = {}

  // 收藏
  updateInfo.collection = true

  try {
    const result = await db.collection('products').where({
      _id: '5e46523c85810427fc9cf275'
    }).update({
      data: updateInfo
    }).field({
      _id: true
    }).get()
    return result
  } catch (error) {
    return error
  }
}

// 这里返回的是一整个list
const test21 = async (event, context) => {
  try {
    const result = await db.collection('collections').where({
      productId: '111',
      list: _.elemMatch({
        appid: _.eq('appid001'),
        openid: _.eq('open001')
      })
    }).get()

    return result
  } catch (error) {
    return error
  }
}

const test22 = async (event, context) => {
  const appid = 'appid001'
  const openid = 'open001'

  try {
    // 找到属于文章的id productId
    // 然后找到这个记录中的list数组中的，满足appid和openid的元素
    // 修改上一个查询得到的结果的 flag
    const {
      data
    } = await db.collection('collections').where({
      productId: '111',
    }).get()

    const {
      list
    } = data[0]

    list.forEach(e => {
      if (e.appid === appid && e.openid === openid) {
        e.flag = !e.flag
      }
    })

    await db.collection('collections').where({
      productId: '111'
    }).update({
      data: {
        list
      }
    })

    return data
  } catch (error) {
    return error
  }
}

/**
 * 注意，这里有一个十分诡异的地方。
 * 在当前的测试代码中是可以得到结果 productList 的
 * 但是在实际的云函数中，必须使用 Promise.all，详情参考：
 * forwx-examples/index.js 中的 /examples/getCollections
 * 
 * @param {*} event 
 * @param {*} context 
 */
const test23 = async (event, context) => {
  const {
    OPENID: openid,
    APPID: appid,
  } = cloud.getWXContext()

  try {
    let {
      data
    } = await db.collection("collections").where({
      list: {
        appid,
        openid,
        flag: true
      }
    }).get()

    const idList = data.map(e => e.productId)

    let productList = []

    idList.forEach(async _id => {
      const {
        data
      } = await db.collection('products').where({
        _id
      }).get()
      productList.push(data[0])
    })

    return data
    // return idList
    // return productList
  } catch (error) {
    return error
  }
}

const test24 = async (event, context) => {
  const parentId = '5de31d5fb0f80726901430ca'
  const listCount = 5
  const skipCount = 5

  const condition = {
    pCategoryId: parentId,
    status: 1,
    title: _.neq('轮播图')
  }

  const {
    list
  } = await db.collection("products")
    .aggregate()
    .lookup({
      from: 'collections',
      localField: 'collection',
      foreignField: '_id',
      as: 'collection'
    })
    .match(condition)
    // .skip(skipCount * 1)
    // .limit(listCount * 1)
    .sort({
      _id: -1
    })
    .project({
      categoryId: 0,
      pCategoryId: 0
    })
    .end()

  console.log(list)
}

const test25 = async (event, context) => {
  const count = await db.collection("yczs-info")
    .where({}).count()

  if (count > 0) {
    const {
      data
    } = await db.collection("yczs-info")
      .where({}).get()

    return data
  } else {
    return count
  }
}

const test26 = async (event, context) => {
  try {
    await db.collection('products')
      .where({
        _id: '5de38ea0315e052db863942e'
      })
      .update({
        data: {
          imgs: _.pull('testurl')
        }
      })
  } catch (error) {
    console.log(error)
  }
}

// exports.main = test1
// exports.main = test2
// exports.main = test3
// exports.main = test4
// exports.main = test5
// exports.main = test6
// exports.main = test7
// exports.main = test8
// exports.main = test9
// exports.main = test10
// exports.main = test11
// exports.main = test12
// exports.main = test13
// exports.main = test14
// exports.main = test15
// exports.main = test16
// exports.main = test17
// exports.main = test18
// exports.main = test19
// exports.main = test20
// exports.main = test21
// exports.main = test22
// exports.main = test23
// exports.main = test24
// exports.main = test25
exports.main = test26